package com.ruoyi.framework.websocket;

import com.ruoyi.framework.util.SpringBeanUtil;
import com.ruoyi.system.service.ISysUserOnlineService;
import com.ruoyi.system.service.impl.SysUserOnlineServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.Semaphore;

/**
 * websocket 消息处理
 *
 * @author ruoyi
 */
@Slf4j
@Component
@RequiredArgsConstructor
@ServerEndpoint("/websocket/{tokenId}")
public class WebSocketServer {

    /**
     * 默认最多允许同时在线人数100
     */
    public static int socketMaxOnlineCount = 100;

    private static Semaphore socketSemaphore = new Semaphore(socketMaxOnlineCount);

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen( Session session, @PathParam("tokenId") String tokenId) throws Exception {

        System.out.println(tokenId);
        boolean semaphoreFlag = false;
        // 尝试获取信号量
        semaphoreFlag = SemaphoreUtils.tryAcquire(socketSemaphore);
        if (!semaphoreFlag) {
            // 未获取到信号量
            log.error("\n 当前在线人数超过限制数- {}", socketMaxOnlineCount);
            session.close();
        } else {
            ISysUserOnlineService service =  SpringBeanUtil.getBean(SysUserOnlineServiceImpl.class);
            if (!service.selectUserIsOnline(tokenId)) {
                SemaphoreUtils.release(socketSemaphore);
                session.close();
                return;
            }
            WebSocketUsers.put(tokenId, session);

            log.info("\n 建立连接 - {}", session);
            log.info("\n 当前人数 - {}", WebSocketUsers.getUsers().size());
            WebSocketUsers.sendMessageToUserByText(tokenId, session, "连接成功");
        }
    }


    /**
     * 连接关闭时处理
     */
    @OnClose
    public void onClose(Session session, @PathParam("tokenId") String tokenId) {
        log.info("\n 关闭连接 - {}", tokenId);
        // 移除用户
        WebSocketUsers.remove(tokenId);
        // 获取到信号量则需释放
        SemaphoreUtils.release(socketSemaphore);
    }

    /**
     * 抛出异常时处理
     */
    @OnError
    public void onError(Session session, Throwable exception) throws Exception {
        if (session.isOpen()) {
            // 关闭连接
            session.close();
        }
        String sessionId = session.getId();
        log.info("\n 连接异常 - {}", sessionId);
        log.info("\n 异常信息 - {}", exception);
        // 移出用户
        WebSocketUsers.remove(sessionId);
        // 获取到信号量则需释放
        SemaphoreUtils.release(socketSemaphore);
    }

    /**
     * 服务器接收到客户端消息时调用的方法
     */
    @OnMessage
    public void onMessage(String message, Session session,@PathParam("tokenId") String tokenId) {
        String msg = "Do not send any messages.";
        WebSocketUsers.sendMessageToUserByText(tokenId,session, msg);
    }
}
